package com.zx.flow.api.listener;

import com.zx.flow.api.listener.request.FlowContext4Listener;
import com.zx.flow.api.listener.request.FlowOperator4Listener;
import com.zx.flow.api.util.AssertUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FlowEventRegister {

    private static final Map<String, FlowCallbackHandler> HANDLER_MAP = new HashMap<>();

    /**
     * 注册处理器
     *
     * @param flowCode
     * @param handler
     */
    public static synchronized void register(String flowCode, FlowCallbackHandler handler) {
        if (HANDLER_MAP.containsKey(flowCode)) {
            AssertUtil.throwFE("flowCode已经被注册过了");
        }
        HANDLER_MAP.put(flowCode, handler);
    }

    public static void doListener(FlowEvent event) {
        getHandler(event).doListener(event);
    }

    public static List<FlowOperator4Listener> getOperators(FlowEvent event) {
        return getHandler(event).getOperators(event);
    }

    private static FlowCallbackHandler getHandler(FlowEvent event) {
        FlowContext4Listener flowContext = event.getFlowContext();
        FlowCallbackHandler handler = HANDLER_MAP.get(flowContext.getFlowConfigCode());
        AssertUtil.checkNotNull(handler, "handler not found, flowId" + flowContext.getId());
        return handler;
    }
}
